<?php

namespace App\Http\Controllers\Home;

use App\Http\Requests\TopicRequest;
use App\Model\Category;
use App\Model\Topic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TopicController extends Controller
{

    public function __construct ()
    {
        //除了index、show方法不需要登录
        $this->middleware ( 'auth' , [ 'except' => [ 'index' , 'show' ] ] );
    }

    public function index(Request $request)
    {
        $category_id=$request->query('category_id');
        $topics=Topic::where('category_id',$category_id)->paginate(1);
        $topics->withPath('topic?category_id='.$category_id);
        return view('home.topic.index',compact('topics'));
    }


    public function create(Request $request)
    {
//        dd($request->query('category_id'));
        $category=Category::find($request->query('category_id'));
//        dd($category->toarray());
        return view('home.topic.create',compact('category'));
    }


    public function store(TopicRequest $request)
    {
        $topic=auth()->user()->topic()->create($request->all());
        return redirect(route('topic.show',$topic))->with('success','添加成功');
    }


    public function show(Topic $topic)
    {
        return view('home.topic.show',compact('topic','users','isZan'));
    }


    public function edit(Topic $topic)
    {
        $this->authorize('update',$topic);
        $category=Category::find($topic->category_id);
        return view('home.topic.edit',compact('topic','category' ));
    }


    public function update(Request $request, Topic $topic)
    {
        $this->authorize('update',$topic);
        $topic->update($request->all());
        return redirect(route('topic.show',$topic))->with('success','更新成功');
    }


    public function destroy(Topic $topic)
    {
        $this->authorize('update',$topic);
        $topic-delete();
        return back()->with('success','删除成功');
    }
}
